import optparse

import pyglet
from pyglet.gl import *
from pyglet.window import key

import sys

import camera
import isometric

class EditableMap(isometric.Map):
    def __init__(self, filename):
        try:
            self.parse_map(filename)
        except IOError:
            self.load_empty_file()
        self.cursorx = 0
        self.cursory = 0
    
        img = pyglet.image.load("../data/sprites/arrow/arrow.png")
        self.cursor = pyglet.sprite.Sprite(img, 0, 0)

    def draw(self, window, cam):
        isometric.Map.draw(self, window, cam)
        cam.focus(window.width, window.height)
        x, y = isometric.isometric_map_coord_to_world_coord(self.cursorx,
                                                            self.cursory)

        glTranslatef(x + 50 - self.cursor.width/2, y+25, 0)
        self.cursor.draw()

    def move_cursor(self, dx, dy):
        self.cursorx += dx
        self.cursory += dy

    def load_empty_file(self):
        self.tile_layer = []

def main():
    win_width = 1024
    win_height = 786
    
    window = pyglet.window.Window(win_width, win_height)

    if len(sys.argv) < 2: sys.argv.append("new_map.map")

    map = EditableMap(sys.argv[1])

    glClearColor(0, 1, 0, 0)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    cam = camera.Camera((0,0),scale=20)

    @window.event
    def on_draw():
        window.clear()
        cam.focus(window.width, window.height)
        map.draw(window, cam)

    @window.event
    def on_key_press(sym, mod):
        if sym == key.UP:
            cam.y += cam.scale
        if sym == key.DOWN:
            cam.y -= cam.scale
        if sym == key.LEFT:
            cam.x -= cam.scale
        if sym == key.RIGHT:
            cam.x += cam.scale
        if sym == key.MINUS:
            cam.scale *= 2
        if sym == key.PLUS:
            cam.scale /= 2.0
        if sym == key.A:
            map.move_cursor(-1, 0)
        if sym == key.D:
            map.move_cursor(1, 0)
        if sym == key.W:
            map.move_cursor(0, 1)
        if sym == key.S:
            map.move_cursor(0, -1)

    print """Up down left right: Control camera
+ -: zoom in and out
w a s d: Move cursor"""

    pyglet.app.run()
    

if __name__ == "__main__":
    main()
    
